package logic

import (
	"context"

	"googee/common/errorx"
	"googee/service/leaderboard/api/internal/svc"
	"googee/service/leaderboard/api/internal/types"
	"googee/service/leaderboard/rpc/leaderboard"
	"googee/service/user/rpc/user"

	"github.com/fatih/color"
	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type RanklistLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRanklistLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RanklistLogic {
	return &RanklistLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RanklistLogic) Ranklist(req *types.RankListReq) (resp *types.RankListReply, err error) {
	resp = &types.RankListReply{}
	result, err := l.svcCtx.Leaderboard.GetRank(l.ctx, &leaderboard.RankRequest{
		Limit:       req.Limit,
		Offset:      req.Offset,
		Bid:         req.Bid,
		Dense:       false,
		BatchOffset: req.BatchOffset,
		Batchid:     req.BatchId,
	})

	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			if st.Code() == codes.NotFound {
				return nil, errorx.NewCodeErrorNoMsg(100101)
			} else if st.Code() == codes.Internal {
				return nil, errorx.NewCodeError(errorx.INTERNAL_ERROR, "系统内部未知错误")
			}
		} else {
			return nil, errorx.NewCodeError(errorx.INTERNAL_ERROR, "系统内部未知错误")
		}
	}

	// color.Red("Data:%v", result.GetData())
	for _, u := range result.GetData() {
		a := types.RankInfo{
			UserId: u.UserId,
			Score:  u.Score,
			Rank:   u.Rank,
		}
		result, err := l.svcCtx.User.GetUser(l.ctx, &user.IdRequest{Id: u.GetId()})
		if err == nil {
			copier.Copy(&a.Details, result)
		}
		resp.Data.RankInfo = append(resp.Data.RankInfo, a)
		color.Green(" user id:%v,rank=%v,score=%v\n", u.UserId, u.Rank, u.Score)
	}

	resp.Data.BatchId = result.GetBatchid()
	resp.Data.Offset = req.Offset
	resp.Data.Limit = req.Limit

	return
}
